#INCLUDE "PROTHEUS.CH"

USER FUNCTION AtuRegTms()

Processa({|| ProcRot()}, "Atualizando Dados", "Aguarde...")

RETURN NIL

//-----------------------------------------------------------------
STATIC FUNCTION ProcRot()
LOCAL aArea := GetArea()
LOCAL aDULArea :=DUL->(GetArea())
LOCAL aDUYArea := DUY->(GetArea())
LOCAL aSA1Area := SA1->(GetArea())
LOCAL cCodMun := ""
LOCAL cGrpVen := ""
LOCAL cCodCli := ""

dbSelectArea("DUL")
DUL->(dbSetOrder(1)) // DUL_FILIAL+DUL_DDD+DUL_TEL+DUL_SEQEND
DUL->(dbGoTop())

dbSelectArea("DUY")
DUY->(dbSetOrder(6))  // DUY_FILIAL+DUY_EST+DUY_CODMUN

dbSelectArea("SA1")
SA1->(dbSetOrder(1)) // A1_FILIAL+A1_COD+A1_LOJA

ProcRegua(DUL->(RecCount()))

WHILE !DUL->(EOF())
	IncProc()
	cCodCli := IF(EMPTY(DUL->(DUL_CODRED + DUL_LOJRED)), DUL->(DUL_CODCLI + DUL_LOJCLI), DUL->(DUL_CODRED + DUL_LOJRED))
	
	IF !SA1->(dbSeek(xFilial("SA1") + cCodCli))
		DUL->(dbSkip())
		LOOP
	ENDIF
	
	IF DUY->(dbSeek(xFilial("DUY") + SA1->(A1_EST + A1_COD_MUN)))
		cCodMun := DUY->(DUY_EST+DUY_CODMUN)
		cGrpVen := DUY->DUY_GRPVEN
		DUY->(dbSkip())
		
		WHILE !DUY->(EOF()) .And. DUY->(DUY_EST + DUY_CODMUN) == cCodMun 
			IF !EMPTY(DUY->DUY_GRPSUP)
				cGrpVen := DUY->DUY_GRPVEN
			ENDIF
			DUY->(dbSkip())
		END WHILE
		
		IF !EMPTY(cGrpVen)
			DUL->(RecLock("DUL", .F.))
				DUL->DUL_CDRDES := cGrpVen
			DUL->(MsUnlock())
		ENDIF
	ENDIF
	DUL->(dbSkip())
END WHILE

DUL->(dbCloseArea())
DUY->(dbCloseArea())
SA1->(dbCloseArea())
RestArea(aArea)
RestArea(aDULArea)
RestArea(aDUYArea)
RestArea(aSA1Area)

RETURN NIL

//-----------------------------------------------------------------